package com.ebelter.btcomlib.bases.activity;


import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;


import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import android.support.annotation.Nullable;

import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;

import com.ebelter.btcomlib.CommonLib;

import com.ebelter.btcomlib.models.bluetooth.blueservices.BlueBackRunService;
import com.ebelter.btcomlib.utils.KeyBoardShowListener;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.utils.ServiceUtil;
import com.ebelter.btcomlib.utils.StatusBarUtil;

import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.dialogs.LoadingDialog;

import butterknife.ButterKnife;


public abstract class BaseActivity extends FragmentActivity {
    private static final String TAG = "BaseActivity";

    public static final int resultCodeSuccess = 1;
    public static final int resultCodeFailure = 2;

    private StationListener mStationListener;

    public KeyBoardShowListener keyBoardShowListener = new KeyBoardShowListener(this);


    public static String getString_(int resId) {
        return CommonLib.APPContext.getString(resId);
    }


    private static final String[] permissions = new String[]{
            Manifest.permission.BLUETOOTH,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_ADMIN};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置无标题


        if (isFullScreen()){//设置是否全屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(loadLayoutById());


        if (isSetTranslucent()){//设置状态栏是否透明
            StatusBarUtil.setTranslucent(this, 0);
        }
        //设置状态栏的字体颜色
        StatusBarUtil.setDarkStatusIcon(this,false);

        checkPermissions();

        ButterKnife.bind(this);

        initView();
        initData();



        if (isOpenNetStationListener()||isOpenTimeChangeListener()||isOpenBlueStationListener()){//只要有一个广播监听器打开就要开启广播
            mStationListener=new StationListener();
            //只要有一个监听器打开这个广播就要打开
            IntentFilter filter = new IntentFilter();
            if (isOpenNetStationListener()){//判断网络状态监听器是否需要打开
                filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            }

            if (isOpenTimeChangeListener()){//判断时间监听器是否需要打开
                filter.addAction(Intent.ACTION_TIME_TICK);
            }

            if (isOpenBlueStationListener()){
                filter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
                filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
                filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
                filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
                filter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
                filter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
            }

            registerReceiver(mStationListener, filter);
        }




        if (isBandBlueService()){//是否需要绑定服务
            runSocketService();//如果后台服务没有开启的情况下 就先开启后台服务
            Intent intent = new Intent(this, BlueBackRunService.class);
            blueServiceConn = new BlueServiceConn();//绑定服务
            bindService(intent, blueServiceConn, BIND_AUTO_CREATE);
        }
    }


    private void checkPermissions() {//1
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        for (String p:permissions){
            // 首先是判断
            if (ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                LogUtils.i(TAG,"权限"+p+"没有授权成功1");
                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                    // 显示弹框给用户的解释 采用系统的
                    LogUtils.i(TAG,"权限"+p+"没有授权成功2--shouldShowRequestPermissionRationale");
                    ActivityCompat.requestPermissions(this, new String[]{p}, 1);
                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this, new String[]{p}, 1);
                    LogUtils.i(TAG,"权限"+p+"没有授权成功3--requestPermissions--"+p);
                }
            }else {
                LogUtils.i(TAG,"权限"+p+"-----授权成功");
            }
        }
        }
    }



    public boolean isSetTranslucent(){
        return true;
    }


    //如果后台服务没有开启的情况下 开启
    protected void runSocketService(){
        if (!ServiceUtil.isRunning(getApplicationContext(),"com.ebelter.btproduces.models.bluetooth.blueservices.BlueBackRunService")){
            //混合调用 为了把服务所在进程变成服务进程
            Intent intent = new Intent(this, BlueBackRunService.class);
            startService(intent);
        }
    }

    protected void initData() {
    }

    protected void initView() {
    }

    protected abstract int loadLayoutById() ;

    protected boolean isFullScreen(){
        return false;
    };

    protected boolean isBandBlueService(){
        return false;
    };


    //是否开启网络状态监听器
    protected boolean isOpenNetStationListener(){
        return false;
    }

    //是否开启蓝牙状态状态监听器
    protected boolean isOpenBlueStationListener(){
        return false;
    }

    protected void bluetoothStationReceive(Intent intent,String action){

    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        NetUtils.getInstance().cancelTag(this);

        if (isOpenNetStationListener()||isOpenTimeChangeListener()||isOpenBlueStationListener()){//反注册网络监听器
            if (mStationListener!=null)unregisterReceiver(mStationListener);
        }

        if (isBandBlueService()){
            unbindService(blueServiceConn);
        }
    }

    public boolean isOpenTimeChangeListener() {
        return false;
    }


    private class StationListener extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent==null)return;
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)){
                return;
            }

            //网络状态变化
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
                int netWorkState = NetUtils.getNetWorkState(context);
                netStationChange(netWorkState);

            }else if (Intent.ACTION_TIME_TICK.equals(action)){//时间分钟变化

                timeChange(0);
            }

            bluetoothStationReceive(intent,action);

        }
    }



    /**

    public static final int NETWORK_NONE = -1;
    public static final int NETWORK_MOBILE = 0;
    public static final int NETWORK_WIFI = 1;
     */
    protected void netStationChange(int netWorkState){

    }

    /**
     * 0分钟变化
     */
    protected void timeChange(int which){

    }
    private LoadingDialog loadingDialog;
    public void showLoadingDialog(String tip){
        if (loadingDialog==null){
            loadingDialog=new LoadingDialog(this);
        }
        if (!loadingDialog.isShowing()){
            loadingDialog.show();
        }
        loadingDialog.setTip(tip);

    }

    public void dissLoadingDialog(){
        if (loadingDialog!=null&&loadingDialog.isShowing()){
            loadingDialog.cancel();
        }
    }


    protected void startActivity(Class<?> cls){
        startActivity(new Intent(this,cls));
    }

    protected void startActivity(Class<?> cls, Bundle bundle){
        Intent intent=new Intent(this,cls);
        intent.putExtra("bundle",bundle);
        startActivity(intent);
    }

    protected Bundle getIntentBundle(){
        return getIntent().getBundleExtra("bundle");
    }



    protected BlueBackRunService.MyBinder myBlueBinder;
    protected BlueServiceConn blueServiceConn;
    private boolean blueBondSuccess=false;

    class BlueServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtils.e(TAG, "-----------------onServiceConnected()");
            myBlueBinder = (BlueBackRunService.MyBinder) service;//绑定服务成功 拿到这个后台服务对象
            blueBondSuccess=true;
            blueServiceConn(true);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.e(TAG, "-----------------onServiceDisconnected()");//绑定服务失败
            myBlueBinder = null;
            blueBondSuccess=false;
            blueServiceConn(false);
        }

    }

    //界面绑定住服务的回到器
    protected void blueServiceConn(boolean blueBondSeviceSuccess){

    }




}
